/*
 * @Autor: CQJ
 * @Date: 2022-08-15 13:41:15
 * @LastEditors: CQJ
 * @LastEditTime: 2022-08-20 18:21:55
 * @Description:
 */
import router from '@/router';
import { ElMessage } from 'element-plus';
import useStore from '@/store';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
NProgress.configure({ showSpinner: false }); // 进度环显示/隐藏
const initMenus = (to: any, from: any) => {


  const { permission } = useStore();
  let pointRouters = []
  const arr = ['sites']
  if (arr.includes(from.name)) {
    pointRouters = permission.originRouter.filter(item => item.name === to.name) || [];
  }
  // else if (from.path.includes('game-box')) {
  //   pointRouters = permission.routes.filter(item => item.name === 'GameBox')[0].children || [];
  // } else {
  //   pointRouters = permission.routes.filter(item => item.name !== 'PopularizeManage' && item.name !== 'GameBox') || [];
  // }
  permission.setRoutes(pointRouters)
};
// 白名单路由
const whiteList = ['/login'];

router.beforeEach(async (to, from, next) => {
  NProgress.start();
  console.log('from: ', from, to);
  const { user, permission } = useStore();
  const hasToken = user.token;
  if (hasToken) {
    // 登录成功，跳转到首页
    if (to.path === '/login') {
      next({ path: '/' });
      NProgress.done();
    } else {
      const hasGetUserInfo = user.roles.length > 0;
      if (hasGetUserInfo) {
        if (to.matched.length === 0) {
          // initMenus(to, from)
          from.name ? next({ name: from.name as any }) : next('/401');
        } else {
          next();
        }
      } else {
        try {
          await user.getUserInfo();
          const roles = user.roles;
          const accessRoutes: any = await permission.generateRoutes(roles);
          accessRoutes.forEach((route: any) => {
            router.addRoute(route);
          });
          next({ ...to, replace: true });
        } catch (error) {
          // 移除 token 并跳转登录页
          await user.resetToken();
          ElMessage.error((error as any) || 'Has Error');
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    // 未登录可以访问白名单页面(登录页面)
    if (whiteList.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  NProgress.done();
});
